<template>
  <div class="chat-container">
    <!-- 左侧患者列表 -->
    <div class="patient-list">
      <h3>患者列表</h3>
      <el-scrollbar height="calc(100vh - 180px)">
        <div 
          class="patient-item" 
          v-for="patient in patientList" 
          :key="patient.userId"
          :class="{ active: currentPatient?.userId === patient.userId }"
          @click="selectPatient(patient)"
        >
          <el-avatar :size="40" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
          <div class="patient-info">
            <div class="name">{{ patient.username }}</div>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <div class="chat-header" v-if="currentPatient">
        <el-avatar :size="32" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
        <span>{{ currentPatient.username }}</span>
      </div>
      <div class="chat-placeholder" v-else>
        <el-empty description="请选择一位患者开始聊天" />
      </div>
      
      <template v-if="currentPatient">
        <!-- 聊天记录 -->
        <div class="chat-messages">
          <el-scrollbar height="calc(100vh - 280px)" ref="messageScrollbar" always>
            <div class="message-list">
              <div class="message-item" v-for="msg in currentMessages" :key="msg.messageId">
                <div class="message-time">{{ formatDateTime(msg.timestamp) }}</div>
                <div class="message-content" :class="{ 'message-right': msg.senderRole === 1 }">
                  <el-avatar 
                    :size="32" 
                    :src="msg.senderRole === 0 
                      ? 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png' 
                      : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" 
                  />
                  <div class="message-bubble">
                    {{ msg.content }}
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>

        <!-- 输入框区域 -->
        <div class="input-area">
          <el-input
            v-model="messageInput"
            type="textarea"
            :rows="3"
            placeholder="请输入消息"
            @keyup.enter.ctrl="sendMessage"
          />
          <el-button type="primary" class="send-btn" @click="sendMessage">发送</el-button>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { listMessage, addMessage } from '@/api/message'
import { listUser } from '@/api/user'
import { listConversation, addConversation } from '@/api/conversation'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const messageInput = ref('')
const currentPatient = ref(null)
const patientList = ref([])
const currentMessages = ref([])
const currentConversationId = ref(null)
const messageScrollbar = ref(null)

// 获取当前登录用户信息（护工）
const getCurrentUser = () => {
  if (!userStore.isLoggedIn) {
    userStore.loadUserInfo()
  }
  return {
    userId: userStore.userId,
    username: userStore.username
  }
}

// 获取患者列表
const getPatientList = async () => {
  try {
    const res = await listUser({})
    patientList.value = res || []
  } catch (error) {
    console.error('获取患者列表失败:', error)
    ElMessage.error('获取患者列表失败，请重试')
  }
}

// 获取会话ID
const getConversationId = async (userId) => {
  const currentUser = getCurrentUser()
  if (!currentUser || !currentUser.userId) {
    console.error('未获取到用户信息')
    return null
  }

  try {
    // 查询患者与护工之间的会话
    const query = {
      userId: userId, // 患者ID
      caregiverId: currentUser.userId // 护工ID
    }
    
    const conversations = await listConversation(query)
    
    if (Array.isArray(conversations) && conversations.length > 0) {
      // 存在会话，返回会话ID
      return conversations[0].conversationId
    } else {
      // 不存在会话，创建新会话
      const newConversation = {
        userId: userId, // 患者ID
        caregiverId: currentUser.userId, // 护工ID
        createTime: new Date().toISOString()
      }
      
      const result = await addConversation(newConversation)
      return result.conversationId
    }
  } catch (error) {
    console.error('获取会话ID失败:', error)
    ElMessage.error('获取会话失败，请重试')
    return null
  }
}

// 获取消息记录
const getMessageList = async (conversationId) => {
  if (!conversationId) {
    return []
  }

  try {
    const messages = await listMessage({ conversationId })
    return messages || []
  } catch (error) {
    console.error('获取消息记录失败:', error)
    ElMessage.error('获取消息记录失败，请重试')
    return []
  }
}

// 选择患者
const selectPatient = async (patient) => {
  // 先清空当前消息列表
  currentMessages.value = []
  // 设置当前选中的患者
  currentPatient.value = patient

  try {
    // 获取会话ID
    const conversationId = await getConversationId(patient.userId)
    
    if (conversationId) {
      // 保存当前会话ID
      currentConversationId.value = conversationId
      
      // 获取消息记录
      const messages = await getMessageList(conversationId)
      
      if (messages.length > 0) {
        currentMessages.value = messages
        console.log(`找到与患者 ${patient.username} 的会话，共 ${messages.length} 条消息`)
      } else {
        // 空消息列表，不显示默认欢迎消息
        console.log(`与患者 ${patient.username} 的会话没有消息记录`)
      }
    }
  } catch (error) {
    console.error('选择患者失败:', error)
    ElMessage.error('选择患者失败，请重试')
  }

  // 滚动到底部
  scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageScrollbar.value) {
      const scrollbarEl = messageScrollbar.value.$el.querySelector('.el-scrollbar__wrap')
      if (scrollbarEl) {
        scrollbarEl.scrollTop = scrollbarEl.scrollHeight
      }
    }
  })
}

// 格式化时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
}

// 发送消息
const sendMessage = async () => {
  if (!messageInput.value.trim()) {
    ElMessage.warning('请输入消息内容')
    return
  }

  if (!currentPatient.value) {
    ElMessage.warning('请先选择患者')
    return
  }

  if (!currentConversationId.value) {
    ElMessage.warning('会话未建立，请重新选择患者')
    return
  }

  const currentUser = getCurrentUser()
  if (!currentUser || !currentUser.userId) {
    ElMessage.warning('未获取到用户信息，请重新登录')
    return
  }

  try {
    const messageData = {
      conversationId: currentConversationId.value,
      senderRole: 1, // 护工角色
      senderId: currentUser.userId,
      content: messageInput.value.trim(),
      timestamp: new Date().toISOString()
    }
    
    // 先添加到本地显示，提供即时反馈
    const tempMessage = {
      ...messageData,
      messageId: 'temp-' + Date.now()
    }
    currentMessages.value.push(tempMessage)
    
    // 清空输入框
    messageInput.value = ''
    
    // 滚动到底部
    scrollToBottom()
    
    // 发送到服务器
    await addMessage(messageData)
    
    // 重新获取消息列表以确保同步
    const updatedMessages = await getMessageList(currentConversationId.value)
    currentMessages.value = updatedMessages
    
    console.log('消息发送成功')
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败，请重试')
  }
}

onMounted(async () => {
  await getPatientList()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 100px);
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.patient-list {
  width: 240px;
  border-right: 1px solid #e4e7ed;
  padding: 20px;
}

.patient-list h3 {
  margin: 0 0 20px 0;
  font-size: 16px;
  color: #303133;
}

.patient-item {
  display: flex;
  align-items: center;
  padding: 12px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.patient-item:hover {
  background-color: #f5f7fa;
}

.patient-item.active {
  background-color: #ecf5ff;
}

.patient-info {
  margin-left: 12px;
}

.patient-info .name {
  font-size: 14px;
  color: #303133;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  gap: 10px;
}

.chat-placeholder {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chat-messages {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.message-list {
  padding: 20px;
}

.message-item {
  margin-bottom: 20px;
}

.message-time {
  text-align: center;
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.message-content {
  display: flex;
  align-items: flex-start;
}

.message-content.message-right {
  flex-direction: row-reverse;
}

.message-bubble {
  margin: 0 12px;
  padding: 10px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  color: #303133;
  max-width: 60%;
}

.message-right .message-bubble {
  background-color: #ecf5ff;
}

.input-area {
  padding: 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 12px;
}

.send-btn {
  align-self: flex-end;
}
</style> 